package com.bdqn.controller;

import com.bdqn.mapper.SysUserMapper;
import com.bdqn.pojo.SysUser;
import com.bdqn.service.SysUserService;
import com.bdqn.util.Constants;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * IndexController
 *
 * @author LILIBO
 * @since 2024/7/27
 */
@Controller
public class IndexController {

    /**
     * 引入业务逻辑层
     */
    @Resource
    private SysUserService sysUserService;

    /**
     * 去登录页
     */
    @GetMapping("/login")
    public String toLogin() {
        // 加载页面渲染需要的资源
        return "login";
    }

    /**
     * 执行登录操作
     */
    @PostMapping("/login")
    public String doLogin(HttpServletRequest request, HttpSession session, @RequestParam("account") String account, @RequestParam("password") String password) {

        SysUser sysUser = sysUserService.login(account, password);
        if (sysUser == null) {
            request.setAttribute("error","账号或密码错误，请重新输入");
            //验证失败 跳转到登录页
            return "login";
        }
        //将用户信息设置到Session作用域
        session.setAttribute(Constants.USER_SESSION, sysUser);
        // 跳转到首页
        return "redirect:/frame";  // redirect：重定向（让浏览器发起请求）
    }

    /**
     * 跳转到首页
     */
    @GetMapping("/frame")
    public String toFrame(){
        return "frame";
    }

    /**
     * 退出登录
     */
    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute(Constants.USER_SESSION); // 删除Session
        session.invalidate(); // 销毁Session
        return "login";
    }

}
